package PhotoUploader
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.events.ProgressEvent;
	import flash.geom.Rectangle;
	import flash.net.FileReference;
	import flash.net.FileFilter;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.Timer;
	import flash.external.ExternalInterface;
	
	/**
	 * ...
	 * @author sergzach
	 */
	public class Main extends Sprite 
	{
		[ Embed( source = "../../lib/add-img.gif" ) ] private var AddImage: Class;
		[ Embed( source = "../../lib/upload.png" ) ] private var UploadImage: Class;
		private var addImage: Bitmap = new AddImage();
		private var uploadImage: Bitmap = new UploadImage();
		
		private var mc: MovieClip = new MovieClip();
		private var fr: FileReference = new FileReference();
		
		// progress graphics
		private var fillBorder:int = 20;
		private var fillTop:int = 140;
		private var fillHeight:int = 5;
		private var dashedStep:int = 5;
		
		private var uploadRoot;
		
		private var userId: String;	
		
		public function Main():void 
		{			
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{			
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			
			// read user_id
			var loaderInfo = this.root.loaderInfo;
			userId = loaderInfo.parameters[ 'user_id' ];
			uploadRoot = loaderInfo.parameters[ 'uploadRoot' ];
			//userId = "699728001";
			
			mc.addChildAt( addImage, 0 );		
			
			mc.buttonMode = true;
			
			addChild( mc );
			
			mc.addEventListener( MouseEvent.CLICK, onBrowse );
			
			fr.addEventListener(Event.SELECT, selectHandler); 
			fr.addEventListener(Event.OPEN, openHandler); 
			
			fr.addEventListener(ProgressEvent.PROGRESS, progressHandler); 			
			
			fr.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadResponse );
		}
		
		private var data: String;
		
		private function uploadResponse( event: DataEvent )
		{
			// start to fade out				
			timer.addEventListener( TimerEvent.TIMER, onFadeOutTimer );
			timer.start();	
			
			data = event.data;
		}
		
		
		private function onBrowse( e ): void
		{
			fr.cancel();	
			fr.browse( [ new FileFilter( "Images", "*.jpg;*jpeg;*.gif;*.png;*.bmp" ) ] );
		}
		
		private function selectHandler(event:Event):void 
		{
			var request:URLRequest = new URLRequest(); 
			request.url = uploadRoot + userId + "/"; 
			request.method = URLRequestMethod.POST;		
			
			fr.upload(request, 'file' ); 
			
			mc.removeChildAt( 0 );				
			mc.addChild( uploadImage );
			
			mc.removeEventListener( MouseEvent.CLICK, onBrowse );
		}
		
		private function openHandler(event:Event):void 
		{			
		}
		
		private function getDrawEnd()
		{
			return stage.stageWidth - fillBorder - dashedStep;
		}
		
		// reset progress graphics
		private function resetProgress()
		{
			var color = 255 << 24 | 228 << 16 | 228 << 8 | 228; // bk
			
			uploadImage.bitmapData.fillRect( new Rectangle( fillBorder, fillTop, getDrawEnd(), fillHeight ), color );
		}
		
		private function progressHandler(event:ProgressEvent):void 
		{			
			var color = 255 << 24 | 120 << 16 | 120 << 8 | 120;
			
			var progress = event.bytesLoaded / event.bytesTotal;		
			
			var drawEnd = progress * getDrawEnd();
			
			for ( var pos = fillBorder; pos < drawEnd; pos += 2 * dashedStep )
			{
				uploadImage.bitmapData.fillRect( new Rectangle( pos, fillTop, dashedStep, fillHeight ), color );
			}			
		}
		
		private var timerDelay: int = 50;
		private var timerTotalTime: Number = 250;
		private var timerCounter: int = 0;
		var timer: Timer = new Timer( timerDelay );
		
		private function reset()
		{			
			mc.removeChildAt( 0 );				
			uploadImage.alpha = 1;
			mc.addChild( addImage );
			mc.addEventListener( MouseEvent.CLICK, onBrowse );
			timerCounter = 0;
			
			resetProgress();
		}
		
		private function onFadeOutTimer( event:Event ):void 
		{			
			timerCounter += timerDelay;				
			
			if ( timerCounter > timerTotalTime )
			{
				timer.stop();
				ExternalInterface.call( 'onUpload', data );
				reset();
			}
			else
			{
				uploadImage.alpha = ( timerTotalTime - timerCounter ) / timerTotalTime;
			}
		}	
		
	}
	
}